﻿using Configuration;
using PLC;
using PLC.Base;
using PLC.Manager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Pumptester.test
{
    public partial class EnvDataReader : Form
    {
        public EnvDataReader()
        {
            InitializeComponent();
        }

     
        
        private void EnvDataReader_Load(object sender, EventArgs e)
        {
            this.textBoxIP.Text = PLCConfig.IP;
            this.textBoxRack.Text = PLCConfig.Rack.ToString();
            this.textBoxSlot.Text = PLCConfig.Slot.ToString();
            this.textBoxConnectionType.Text = PLCConfig.ConnectionType.ToString();

            this.textBoxPort.Text = ModBusConfig.PortName;
            this.textBoxBaudRate.Text = ModBusConfig.BaudRate.ToString();
            this.textBoxParity.Text = ModBusConfig.Parity.ToString();
            this.textBoxDataBits.Text = ModBusConfig.DataBits.ToString();
            this.textBoxStopBits.Text = ModBusConfig.StopBits.ToString();
            this.textBoxReadTimeOut.Text = ModBusConfig.ReadTimeOut.ToString();
            this.dataReadHandle = dataFetch_After;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {

                dataManager = EnvDataManagerSimpleFactory.createEnvDataManager(EnvDataConfig.EnvDataType);
                //dataManager.init(int.Parse(this.textBoxDN.Text), float.Parse(this.textBoxTransformationRatio.Text));
                dataManager.Open();
                this.textBoxDN.ReadOnly = true;
                this.textBoxTransformationRatio.ReadOnly = true;
                readFlag = true;
                ReadData();
                this.readFlag = true;
                this.btnOpenClose.Enabled = false;
                this.btnClose.Enabled = true;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            readFlag = false;
            dataManager.Close();
            this.textBoxDN.ReadOnly = false;
            this.textBoxTransformationRatio.ReadOnly = false;
            this.btnOpenClose.Enabled = true;
            this.btnClose.Enabled = false;

        }

        IEnvDataManager dataManager;
        Thread threadReadData = null;
        EnvData currentEnvData;
        private object lockObject = new object();
        bool readFlag = false;
        System.Timers.Timer timer;

        private void startReadThread()
        {
            threadReadData = new Thread(new ThreadStart(ReadData));
            threadReadData.IsBackground = true;
            threadReadData.Start();
        }

        

        /// <summary>
        /// 从硬件获取到数据后，计算，并且填入界面
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private void dataFetch_After(EnvData data)
        {
            this.textBoxCurrent.Text = data.Current.ToString();
            this.textBoxVoltage.Text = data.Voltage.ToString();
            this.textBoxActivePower.Text = data.ShaftPower.ToString();
            this.textBoxPresureIn.Text = data.ShaftPower.ToString();
            this.textBoxPresureOut.Text = data.PresureOut.ToString();
            this.textBoxFlow.Text = data.Flow.ToString();
            this.textBoxTemperature.Text = data.Temperature.ToString();
            this.textBoxSpeed.Text = data.Speed.ToString();
            this.textBoxPowerfactor.Text = data.Powerfactor.ToString();
        }

        protected delegate void DataReadHandle(EnvData message);

        protected DataReadHandle dataReadHandle = null;


        private void After_ReadData(EnvData data)
        {
            if (dataReadHandle == null)
            {
                return;
            }
            if (this.InvokeRequired)
            {
                try
                {
                    this.Invoke(dataReadHandle, new object[] { data });
                }
                catch
                {
                }
            }

        }

        private void ReadData()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Enabled = true;
            timer.AutoReset = false;//设置是执行一次（false）还是一直执行(true)；  
            timer.Start();
            

            timer.Elapsed += (o, a) =>
            {
                try
                {
                    if (!readFlag)
                    {
                        return;
                    }
                    DynamicParams dynamicParams = new DynamicParams(int.Parse(this.textBoxDN.Text), double.Parse(this.textBoxTransformationRatio.Text),544);
                  
                    EnvData data = this.dataManager.ReadData(dynamicParams);
                    After_ReadData(data);
                    lock (lockObject)
                    {
                        if (data != null)
                        {
                            this.currentEnvData = (EnvData)data.Clone();
                        }
                    }
                    timer.Start();

                }
                catch
                {
                }
            };

        }
    }
}
